<template>
  <el-card>
    <div slot="header">
      <h3>修改进价</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <el-button
          v-if="showBtn('高级关联')"
          type="text"
          size="large"
          icon="el-icon-link"
          @click="handleSeniorAssociated"
        >高级关联</el-button
        >
        <el-button
          v-if="showBtn('关联商品')"
          type="text"
          size="large"
          @click="handleAssociatedGoods"
          >关联商品</el-button
        >
        <el-button
          v-if="infoData.length > 0"
          type="text"
          size="large"
          @click="handleExportData"
          :loading="exportLoading"
          >模板导出</el-button
        >
        <a
          ><Upload
            :show-upload-list="false"
            :format="['xlsx', 'xls', 'csv']"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-format-error="handleUploadFormatError"
            :before-upload="handleBeforeUpload"
            :action="`${uploadBaseURL}sysback/supplyareaprice/importTemplate`"
            ><el-button type="text" size="large">模板导入</el-button></Upload
          ></a
        >
        <el-button
          v-if="canOpeState"
          type="text"
          size="large"
          @click="handleSaveData('save')"
          :loading="saveLoading"
          :disabled="infoData.length == 0"
          >暂存</el-button
        >
        <el-button
          v-if="canOpeState"
          type="text"
          size="large"
          @click="handleSaveData('submit')"
          :loading="saveLoading"
          :disabled="infoData.length == 0"
          >提交</el-button
        >
        <el-button
          v-if="isFormEditPage"
          type="text"
          size="large"
          @click="handleGoBack"
        >返回</el-button>
      </el-row>
      <el-row>
        <el-form size="mini" ref="updatePriceForm" :model="updatePriceForm" label-width="140px">
          <el-col :span="5">
            <el-form-item label="是否自动调整售价：">
              <el-select v-model="updatePriceForm.isAdjustSalePrice" placeholder="请选择">
                <el-option
                  v-for="item in autoModifySalepriceOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="19">
            <el-form-item v-show="!updatePriceForm.isAdjustSalePrice" label="不调售价原因：">
              <el-input maxlength="200" :rows="1" type="textarea" v-model.trim="updatePriceForm.reason"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row>
        <skus-table
          :loading="tableLoading"
          :data-source="infoData"
          :columns="infoColumns"
          @handleRowChange="handleRowChange"
          @handleCancelSelect="handleCancelSelect"
        />
      </el-row>
      <FooterFields :footerFields="footerFields" />
    </div>
    <link-modal
      ref="link"
      :pageType="0"
      :goodsType="'2'"
      :dialog-visible="diaVisible"
      :column="linkColumns"
      :skuRows="skuRows"
      :maxLinkedNum="maxLinkedNum"
      @returnList="getChildList"
      @addSkuRows="addSkuRows"
      @removeSkuRows="removeSkuRows"
    />
    <SeniorLinkedDialog
      :visible.sync="seniorAssociated.visible"
      :columns="seniorAssociated.columns"
      :dataSource="seniorAssociated.dataSource"
      @seniorSearchResult="getSeniorResultFn"
    />
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import linkModal from './comps/linkModalForSupply.vue';
import SkusTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import { generateUuid, isResponseSuccess, createExcelByExport } from '@/utils/bizUtils';
import { handlePriceChangeForSingleModify } from '@/utils/price';
import { EDIT_ENTER_PRICE_INFO_AMOUNT, EDIT_PURCHASE_MAX_LINKED_AMOUNT } from '@/constants/exportAmountLimit';
import { ENTER_PRICE_SINGLE_COLUMNS, LINK_COLUMNS, ERRORS_COLUMN, TIPS_COLUMN } from '@/pages/commodity/modules/constants/purchaseModule/enterPrice';
import { requestToExport } from '@/api/commonHttp';
import { getCanOpeState } from '@/utils/getUtils';
export default {
  components: {
    linkModal,
    FooterFields,
    SkusTable,
    SeniorLinkedDialog
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      updatePriceForm: {
        isAdjustSalePrice: true,
        reason: ''
      },
      autoModifySalepriceOption: [
        { label: '是', value: true },
        { label: '否', value: false }
      ],
      maxLinkedNum: EDIT_PURCHASE_MAX_LINKED_AMOUNT,
      isSeniorQuery: false, // 是否是高级关联，true是，false为普通关联
      supplyAreaPriceNewParams: [], // 高级关联，导出所需参数
      seniorAssociated: {
        visible: false,
        columns: [
          {
            label: '供应商编码',
            prop: 'supplyCode',
            type: 'textarea'
          },
          {
            label: 'SKU编码',
            prop: 'skuNo',
            type: 'textarea'
          }
        ],
        dataSource: [
          {
            supplyCode: '',
            skuNo: ''
          }
        ]
      },
      exportLoading: false,
      submitLoading: false,
      saveLoading: false,
      tableLoading: false,
      skuRows: [],
      supplyUuids: [],
      diaVisible: false, // 关联商品 弹窗
      isReady: false,
      tabsValue: 'linkno', // 切换tabs
      recordNo: '', // 进入页面获取的单据号
      saveinfo: {},
      linkColumns: LINK_COLUMNS,
      infoColumns: [],
      infoData: [],
      infoDataInit: [],
      skuNo: '',
      productUuid: '',
      tiaojiarecordNo: '',
      footerFields: {},
      rawMaterialTodoRecordNo: ''
    };
  },
  created () {
    this.setCanOpeState()
    const { rawMaterialTodoRecordNo, recordNo, recordNo2 } = this.$route.query;
    this.recordNo = recordNo;
    this.tiaojiarecordNo = recordNo2;
    // 原材料待办单据号
    this.rawMaterialTodoRecordNo = rawMaterialTodoRecordNo;
    if (this.tiaojiarecordNo) {
      this.getTiaojiaData(this.tiaojiarecordNo);
    }
    if (this.recordNo) {
      this.queryTableDataByRecordNoAction()
    }
    this.generateTableColumns()
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    isFormEditPage () {
      let flag = false;
      if (this.recordNo || this.tiaojiarecordNo) {
        flag = true;
      }
      return flag;
    }
  },
  methods: {
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    handleGoBack () {
      let routeName = 'modifyManageList';
      if (this.recordNo) {
        routeName = 'modifyManageList'
      }
      this.$router.push({ name: routeName });
    },
    // 初始化表头
    generateTableColumns () {
      this.infoColumns = _.cloneDeep(ENTER_PRICE_SINGLE_COLUMNS);
    },
    // 根据recordNo查询表格数据
    queryTableDataByRecordNoAction () {
      this.tableLoading = true;
      ApiRequest(
        '/sysback/supplyareaprice/getUpdateDetailByRecordNo?recordNo=' +
          this.recordNo,
        'post',
        '',
        false
      ).then(res => {
        this.tableLoading = false;
        if (isResponseSuccess(res)) {
          this.updatePriceForm = {
            isAdjustSalePrice: res.retData.canChange !== '2',
            reason: res.retData.launchReason
          }
          this.saveinfo = res.retData;
          this.footerFields = res.retData;
          this.infoData = res.retData.listDetail;
          this.infoData.forEach((item) => {
            this.formatTableData(item)
            this.handleRowChange(item)
          })
        }
      }).catch(() => {
        this.tableLoading = false;
      });
    },
    getTiaojiaData (arr) {
      let skNos = [];
      let supplyCodes = [];
      let datalist = [];
      ApiRequest(
        '/sysback/salepricechangeorder/prepareChangeOrder?recordNo=' + arr,
        'post'
      ).then(res => {
        datalist = res.retData.single;
        res.retData.single.forEach(item => {
          skNos.push(item.skuNo);
          supplyCodes = [item.storeNo];
        });
        skNos = [...new Set(skNos)];
        let data = {
          skuNos: skNos,
          supplyCodes: supplyCodes
        };
        this.tableLoading = true;
        ApiRequest(
          '/sysback/supplyareaprice/getListBySkuNos',
          'post',
          data
        ).then(res => {
          this.tableLoading = false;
          if (isResponseSuccess(res)) {
            this.infoData = [];
            this.infoData = this.infoDataInit.concat(res.retData);
            this.infoData.forEach(item => {
              this.formatTableData(item)
              item.mainUnitCostPriceUpdate = item.mainUnitCostPrice || 0;
              item.packRatioUpdate = item.packRatio || 0;
              item.rebateRatioUpdate = item.rebateRatio || 0;
              item.rebateRatioDescUpdate = item.rebateRatioDesc || '';
              item.processChargesRatioUpdate = item.processChargesRatio || 0;
              item.freightRatioUpdate = item.freightRatio || 0;
              item.factoryFacePriceUpdate = item.factoryFacePrice;
              item.mainPurchasePriceUpdate = item.mainPurchasePrice || 0;
              item.purchasePriceNoteUpdate = item.purchasePriceNote || '';
              if (datalist.length != 0) {
                datalist.forEach(otem => {
                  if (
                    otem.skuNo == item.skuNo &&
                    otem.city == item.templateCityUuid &&
                    otem.storeNo == item.supplyUuid
                  ) {
                    item.mainPurchasePriceUpdate = otem.newUnitPrice;
                  }
                });
              }
              this.handleRowChange(item);
            });
          }
        }).catch(() => {
          this.tableLoading = false;
        });
      });
    },
    /* 返回表单请求数据action */
    getTableDataAction ({ data, url }) {
      this.tableLoading = true;
      ApiRequest(url, 'post', data, false).then(res => {
        this.tableLoading = false;
        if (!isResponseSuccess(res)) {
          return false;
        }
        let list = this.infoDataInit.concat(res.retData);
        list.forEach(item => {
          this.formatTableData(item)
          // 我司进价与竞争对手差额比例
          item.opponentRatio = 0;
          // 落实开票价格
          item.invoicePrice = 0;
          // 厂家调价原因
          item.changePriceReason = '';
          item.packRatioUpdate = item.packRatio || 0;
          item.rebateRatioUpdate = item.rebateRatio || 0;
          item.rebateRatioDescUpdate = item.rebateRatioDesc || '';
          item.processChargesRatioUpdate =
            item.processChargesRatio || 0;
          item.freightRatioUpdate = item.freightRatio || 0;
          item.purchasePriceUpdate = item.purchasePrice || 0;
          item.mainPurchasePriceUpdate = item.mainPurchasePrice || 0;
          item.abnormalPurchaseConvertRatioUpdate =
            item.abnormalPurchaseConvertRatio || 0;
          item.theoryConvertRatioCostPriceUpdate =
            item.theoryConvertRatioCostPrice || 0;
          item.actualConvertRatioCostPriceUpdate =
            item.actualConvertRatioCostPrice || 0;
          item.mainUnitCostPriceUpdate = item.mainUnitCostPrice || 0;
          item.factoryFacePriceUpdate = item.factoryFacePrice;
          // 进价备注
          item.purchasePriceNoteUpdate = item.purchasePriceNote || '';
          // 进价浮动率初始化为零
          item.mainPurchasePriceFloatRadio =
            !!item.mainPurchasePriceFloatRadio || 0;
          item.mainUnitCostFloatPrice =
            !!item.mainUnitCostFloatPrice || 0;
          this.handleRowChange(item);
        });
        this.infoData = list;
      }).catch(() => {
        this.tableLoading = false;
      });
    },
    /* 高级关联事件 */
    handleSeniorAssociated () {
      let curBtnId = getBtnsId('高级关联');
      sessionStorage.setItem('buttonId', curBtnId);
      this.seniorAssociated.visible = true;
    },
    /* 获取高级关联结果方法 */
    getSeniorResultFn (data) {
      this.skuRows = []; // 清空关联商品已关联数据
      this.infoData = []; // 清空关联商品带出的表格数据
      this.isSeniorQuery = true;
      this.supplyAreaPriceNewParams = data;
      this.getTableDataAction({ data, url: '/sysback/supplyareaprice/advanced/getListBySkuNos?isPurchaseMultiUnit=2' });
    },
    // 返回按钮
    backButton () {
      this.$router.push({
        path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageList'
      });
    },
    addSkuRows (row) {
      this.skuRows.push(row);
    },

    removeSkuRows (row) {
      this.skuRows = this.skuRows.filter(item => row.uuid != item.uuid);
    },
    // 取消关联
    handleCancelSelect (data) {
      const { row } = data;
      // this.$delete(this.infoData, index);
      this.infoData = this.infoData.filter(item => item.uuid != row.uuid)
      this.$nextTick(() => {
        this.$message.info('删除成功', 10);
      });
      this.skuRows = this.skuRows.filter(
        item =>
          (item.skuNo == row.skuNo && item.supplyUuid != row.supplyUuid) ||
          (item.skuNo != row.skuNo && item.supplyUuid == row.supplyUuid) ||
          item.skuNo != row.skuNo ||
          item.supplyUuid != row.supplyUuid
      );
    },
    getChildList (uuids) {
      this.handleHideDialog();
      if (uuids.length !== 0) {
        this.isSeniorQuery = false;
        this.getTableDataAction({ data: uuids, url: '/sysback/supplyareaprice/getSupplyAreaPriceInfoByUuids' });
      } else {
        this.infoData = [];
      }
    },
    handleHideDialog () {
      this.diaVisible = false;
    },
    // 展示 关联商品 弹窗
    handleAssociatedGoods () {
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.diaVisible = true;
      // this.$refs.link.getLinkData();
    },
    // 暂存
    handleSaveData (type) {
      if (!this.updatePriceForm.isAdjustSalePrice && !this.updatePriceForm.reason) {
        return this.$message.warning('请填写不调售价原因')
      }
      this.infoData = this.infoDataInit.concat(this.infoData);
      if (this.infoData.length > EDIT_ENTER_PRICE_INFO_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${EDIT_ENTER_PRICE_INFO_AMOUNT}`)
      }
      let data = this.infoData;
      data.forEach((item, index) => {
        item.isMainSupply = '2';
      });
      const params = {
        isSteel: false, // true 多计量, false 单计量（必传）
        isAdjustSalePrice: this.updatePriceForm.isAdjustSalePrice, // 是否调整售价 true 是, false 否（必传）
        reason: this.updatePriceForm.reason, // 是否调整售价为否时需要传原因字段
        supplyAreaPriceDTOS: data, // 参照原修改进价暂存入参的进价集合
        recordNo: this.recordNo || '', // 首次暂存无，后续暂存会更新此单据号，参照原先
        rawMaterialTodoRecordNo: this.rawMaterialTodoRecordNo || '' // 原材料待办单据号
      }
      this.saveLoading = true;
      ApiRequest(
        '/sysback/supplyareaprice/batchUpdateProductSupplyAreaPrice', 'post', params
      ).then(res => {
        this.saveLoading = false;
        if (isResponseSuccess(res)) {
          this.validateFailCallBack(res.retData, type)
        }
      }).catch(() => {
        this.saveLoading = false;
      });
    },
    // 校验异常信息回调
    validateFailCallBack (response, type) {
      const { hasErrorMsg, hasTipMsg, productUpdateCommitRecordDTO, supplyAreaPriceDTOS } = response
      if (!hasErrorMsg) {
        this.saveinfo = productUpdateCommitRecordDTO;
        this.recordNo = productUpdateCommitRecordDTO.recordNo;
        this.footerFields = productUpdateCommitRecordDTO;
        this.$message.success('暂存成功')
      }
      if (!hasErrorMsg && !hasTipMsg && type == 'submit') {
        return this.handleSubmitData()
      }
      this.generateTableColumns()
      if (hasTipMsg) {
        this.infoColumns.unshift(TIPS_COLUMN)
      }
      if (hasErrorMsg) {
        this.infoColumns.unshift(ERRORS_COLUMN)
      }
      // 格式化数据
      supplyAreaPriceDTOS.forEach(item => {
        this.formatTableData(item)
      })
      this.infoData = supplyAreaPriceDTOS;
      // 存在禁止提交原因不允许提交
      if (hasErrorMsg) {
        return this.$alert('存在禁止提交原因，无法提交单据，请在详情页中查看具体原因', '提交错误提示', {
          confirmButtonText: '确定',
          type: 'warning',
        });
      }
      // 存在异常提示展示人要提交按钮
      if (hasTipMsg && type == 'submit') {
        return this.$confirm('存在异常提示，是否仍要提交', '提交异常提示', {
          cancelButtonText: '查看详情',
          confirmButtonText: '仍要提交',
          dangerouslyUseHTMLString: true,
          customClass: 'abnormal-tips'
        })
          .then(() => {
            this.handleSubmitData()
          })
          .catch(() => {});
      }
    },
    // 提交
    handleSubmitData () {
      if (this.saveinfo.recordNo == '') {
        return this.$message.warning('请暂存后再提交');
      }
      this.saveLoading = true;
      let url = `/sysback/supplyareaprice/commitSupplyPrice?recordNo=${this.saveinfo.recordNo}`;
      if (this.tiaojiarecordNo) {
        url = `/sysback/supplyareaprice/commitSupplyPrice?recordNo=${this.saveinfo.recordNo}&salepriceChangeOrderRecordNo=${this.tiaojiarecordNo}`;
      }
      ApiRequest(url, 'post', '', false).then(res => {
        this.saveLoading = false;
        if (isResponseSuccess(res)) {
          this.$message.success('提交成功');
          this.$router.push({ name: 'chageFromManageList' })
        }
      }).catch(() => {
        this.saveLoading = false;
      });
    },
    // 导出表格数据
    async exportTableData (supplyPriceUuids) {
      const uuid = generateUuid()
      const res = await requestToExport({
        url: '/sysback/supplyareaprice/downLoadTemplateForUpdateSupplyPrice',
        type: 'post',
        data: {
          productType: '1', // 1为单计量。2为多计量
          supplyPriceUuids, // 表单要导出的进价数据的uuid集合
          uuid
        }
      }, () => { this.exportLoading = true; }, () => { this.exportLoading = false; });
      createExcelByExport({ res, excelTitle: `进价信息模板_${uuid}.xlsx` });
    },
    // 导出表格
    handleExportData () {
      this.infoData = this.infoDataInit.concat(this.infoData);
      const supplyPriceUuids = _.uniq(this.infoData
        .map(item => item.uuid)
        .filter(item => item)
      );
      if (supplyPriceUuids.length == '0') {
        return this.$message.warning('请先关联商品');
      }
      this.exportTableData(supplyPriceUuids);
    },
    // 上传之前
    handleBeforeUpload (e) {
      this.tableLoading = true;
    },
    // 上传失败
    handleUploadError (response, file, fileList) {
      this.tableLoading = false;
    },
    // 上传成功
    handleUploadSuccess (res) {
      this.tableLoading = false;
      const { retData, retStatus, retMessage } = res;
      if (retStatus != 1) {
        return this.$message.error(retMessage || '导入失败');
      }
      this.$message.success('导入成功');
      retData && retData.forEach(item => {
        this.formatTableData(item)
        this.handleRowChange(item);
      });
      this.infoData = retData.reverse();
    },
    // 格式验证错误
    handleUploadFormatError (file, fileList) {
      this.tableLoading = false;
      this.$Message.error('文件格式错误');
    },

    handleRowChange (row, index) {
      handlePriceChangeForSingleModify(row)
    },
    // 格式化表格数据
    formatTableData (item) {
      if (item.supplyProductInfo) {
        item.productName = item.supplyProductInfo.productName || '';
        item.specDetailStr = item.supplyProductInfo.specDetailStr || '';
      }
      if (item.supplyInfoDTO) {
        item.invoiceType = item.supplyInfoDTO.invoiceType
        item.invoiceTypeName = item.supplyInfoDTO.invoiceTypeName
        item.taxRate = item.supplyInfoDTO.taxRate
      }
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
/deep/ .el-table__body-wrapper{
  z-index: 2
}
</style>
